---
title: "向POJO对象中注入依赖"
categories:
- java
- spring
tags:
---

<div id="content">
<div class="org-src-container">
<pre class="src src-java"><span style="font-style: italic;">/**</span>
<span style="font-style: italic;"> * 假设这是被需要的某个组件</span>
<span style="font-style: italic;"> *</span>
<span style="font-style: italic;"> */</span>
<span style="font-weight: bold; text-decoration: underline;">@Component</span>
<span style="font-weight: bold;">public</span> <span style="font-weight: bold;">class</span> <span style="font-weight: bold; text-decoration: underline;">Converter</span> {

    <span style="font-weight: bold; font-style: italic;">// </span><span style="font-weight: bold; font-style: italic;">do something</span>

}

<span style="font-style: italic;">/**</span>
<span style="font-style: italic;"> * 这是POJO，Component注解是为了让 setConverter 方法注入，</span>
<span style="font-style: italic;"> * setConverter 方法设置静态变量的值</span>
<span style="font-style: italic;"> * 这样，new User() 的对象就能使用Converter组件了，</span>
<span style="font-style: italic;"> * 适用于 明确知道Converter 是单例的情况</span>
<span style="font-style: italic;"> */</span>
<span style="font-weight: bold; text-decoration: underline;">@Component</span>
<span style="font-weight: bold;">public</span> <span style="font-weight: bold;">class</span> <span style="font-weight: bold; text-decoration: underline;">User</span> {

    <span style="font-weight: bold;">static</span> <span style="font-weight: bold; text-decoration: underline;">Converter</span> <span style="font-weight: bold; font-style: italic;">converter</span>;

    <span style="font-weight: bold; text-decoration: underline;">@Autowired</span>
    <span style="font-weight: bold;">public</span> <span style="font-weight: bold; text-decoration: underline;">void</span> <span style="font-weight: bold;">setConverter</span>(<span style="font-weight: bold; text-decoration: underline;">Converter</span> <span style="font-weight: bold; font-style: italic;">converter</span>) {
        User.converter = converter;
    }

    <span style="font-weight: bold; text-decoration: underline;">Long</span> <span style="font-weight: bold; font-style: italic;">id</span>;
    <span style="font-weight: bold; text-decoration: underline;">String</span> <span style="font-weight: bold; font-style: italic;">userId</span>;
    <span style="font-weight: bold; text-decoration: underline;">String</span> <span style="font-weight: bold; font-style: italic;">userName</span>;
    ...

}

</pre>
</div>
</div>
<div class="status" id="postamble">
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
